const AJAX = getApp().ajax,
      $wx = getApp().$wx,
      getColor = getApp().globalData.getColor;

Page({
  data: {
    showBtnStatus: 1,
    showAuthorize: true
  },

  onLoad(options) {
    let shop_config = wx.getStorageSync('shopConfig');
    this.setData({
      shopConfig: shop_config,
      getColor: getColor()
    }, () => {
      $wx.setNavColor(getColor().val);
    });
  },

  //获取用户信息
  getUserInfo(e) {
    let _this = this, user_info = e.detail;
    _this.isAuthorization('userInfo', (status) => {
      if (status) {
        wx.setStorageSync('userInfo', user_info);
        _this.login(user_info.userInfo);
      } else {
        $wx.showToast('请选打开授权！');

        _this.setData({
          showBtnStatus: 2
        });
      }
    });

  },

  //打开授权 
  openSetting(e) {
    let _this = this;
    _this.isAuthorization('userInfo', (status) => {
      if (status) {
        _this.setData({
          showBtnStatus: 1
        });
      }
    });
  },

  /**
   * 登录
   * @param code
   * @param user_nickname
   * @param avatar
   * */
  login(userInfo) {
    let _this = this, td = _this.data;
    wx.login({
      success: loginRes => {
        wx.showLoading({ title: '登录中...'});

        AJAX.login({
          code: loginRes.code,
          user_nickname: userInfo.nickName,
          avatar: userInfo.avatarUrl
        }, (status, data, msg) => {
          wx.hideLoading();
          if (status) {
            wx.setStorageSync('token', data.token);
            let page = getCurrentPages(),
            prve_page = page[1],
            prve_page_pamas = prve_page.options;

            wx.navigateBack({
              success() {
                prve_page.onLoad(prve_page_pamas);
              }
            });
           
          } else {
            $wx.showToast(msg);
          }
        });
      }
    });
  },

  /*是否授权*/
  isAuthorization(type, callback) {
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.' + type]) {
          callback(true);
        } else {
          callback(false);
        }
      }
    })
  }
});